package com.autoglm.android.core.models

import org.json.JSONObject

/**
 * 视觉元素数据类，表示通过视觉分析识别到的界面元素
 */
data class VisualElement(
    val id: String,                    // 元素ID
    val text: String,                  // 元素文本内容
    val bounds: Rect,                  // 元素边界
    val confidence: Float,             // 识别置信度
    val type: com.autoglm.android.core.vision.VisualElementType, // 元素类型
    val clickable: Boolean             // 是否可点击
) {
    /**
     * 元素是否为空（边界无效）
     */
    fun isEmpty(): Boolean {
        return bounds.isEmpty()
    }
    
    /**
     * 获取元素中心点X坐标
     */
    fun getCenterX(): Int {
        return bounds.left + (bounds.right - bounds.left) / 2
    }
    
    /**
     * 获取元素中心点Y坐标
     */
    fun getCenterY(): Int {
        return bounds.top + (bounds.bottom - bounds.top) / 2
    }
    
    /**
     * 转换为JSON对象
     */
    fun toJson(): JSONObject {
        val json = JSONObject()
        json.put("id", id)
        json.put("text", text)
        json.put("confidence", confidence)
        json.put("type", type.name)
        json.put("clickable", clickable)
        
        val boundsJson = JSONObject()
        boundsJson.put("left", bounds.left)
        boundsJson.put("top", bounds.top)
        boundsJson.put("right", bounds.right)
        boundsJson.put("bottom", bounds.bottom)
        json.put("bounds", boundsJson)
        
        return json
    }
    
    companion object {
        /**
         * 从JSON对象创建视觉元素
         */
        fun fromJson(json: JSONObject): VisualElement? {
            try {
                val id = json.getString("id")
                val text = json.getString("text")
                val confidence = json.getDouble("confidence").toFloat()
                val typeStr = json.getString("type")
                val type = com.autoglm.android.core.vision.VisualElementType.valueOf(typeStr)
                val clickable = json.getBoolean("clickable")
                
                val boundsJson = json.getJSONObject("bounds")
                val bounds = Rect(
                    left = boundsJson.getInt("left"),
                    top = boundsJson.getInt("top"),
                    right = boundsJson.getInt("right"),
                    bottom = boundsJson.getInt("bottom")
                )
                
                return VisualElement(
                    id = id,
                    text = text,
                    bounds = bounds,
                    confidence = confidence,
                    type = type,
                    clickable = clickable
                )
            } catch (e: Exception) {
                return null
            }
        }
    }
} 